<?php
declare (strict_types = 1);

namespace app\command\logic;

use app\command\logic\BaseLogic;
use think\console\Output;

/**
 * 统计-商家-订单交易数据
 * php think cli stats_shop_transaction --msg='{"days":30}'
 */
class CliStatsShopTransactionLogic extends BaseLogic implements CliInterface
{

    /**
     * 入口方法
     * {@inheritdoc}
     */
    public function run(Output $output, array $msg): bool
    {
        $insertData = [];
        $date       = isset($msg['date']) ? ($msg['date'] == 'today' ? date('Y-m-d') : $msg['date']) : null;
        if ( ! empty($date)) {
            $items = self::dataForTransaction($date);
            if ( ! empty($items)) {
                foreach ($items as $item) {
                    $insertData[] = $item;
                }
            }
        } else {
            $days = intval($msg['days'] ?? 1);
            for ($i = 1; $i <= $days; $i++) {
                $date = date('Y-m-d', strtotime("-$i days"));
                // echo $date . "\n";exit;
                $items = self::dataForTransaction($date);
                if ( ! empty($items)) {
                    foreach ($items as $item) {
                        $insertData[] = $item;
                    }
                }
            }
        }
        if ( ! empty($insertData)) {
            \think\facade\Db::table('stats_shop_transaction')
                ->replace()
                ->insertAll($insertData);
        }
        return true;
    }

    private static function dataForTransaction($date)
    {
        $end = $date . ' 23:59:59';

        // 订单状态 0待支付 1待发货 2待收货 3已收货 4已完成 5退款中 6退款成功 7取消 8超时取消 9待退货
        //   `order_type` 1线下直付单 2线上单 3线下单 4供应链',
        $field = [
            'shop_id',
            'count(distinct user_id) AS order_member_count',
            'count(*) as order_total', //
            'sum(CASE WHEN pay_at is null THEN 0 ELSE 1 END) AS pay_order_total',
            'sum(pay_price) AS order_total_price', //
            'sum(CASE WHEN pay_at is null THEN 0 ELSE pay_price END) AS pay_order_total_price', //
        ];
        $items = \think\facade\Db::table('order_shop')
            ->field($field)
            ->whereBetweenTime('create_at', $date, $end)
            ->group('shop_id')
            ->select()->toArray();
        // echo \think\facade\Db::table('order_shop')->getlastsql();
        // var_dump($items);exit;
        // $data['date'] = $date;

        //status 售后单状态(0进行中 1 已拒绝 2 审核通过  3 已退货 4已取消 5 已完成)
        $field2 = [
            'shop_id',
            'count(*) refund_order_total',
            'count(distinct user_id) AS refund_member_count',
            'COALESCE(SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END), 0) AS refund_order_0',
            'COALESCE(SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END), 0) AS refund_order_1',
            'COALESCE(SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END), 0) AS refund_order_2',
            'COALESCE(SUM(CASE WHEN status = 3 THEN 1 ELSE 0 END), 0) AS refund_order_3',
            'COALESCE(SUM(CASE WHEN status = 4 THEN 1 ELSE 0 END), 0) AS refund_order_4',
            'COALESCE(SUM(CASE WHEN status = 5 THEN 1 ELSE 0 END), 0) AS refund_order_5',

            'COALESCE(SUM(CASE WHEN status = 0 THEN refund_money ELSE 0 END), 0) AS refund_order_0_price',
            'COALESCE(SUM(CASE WHEN status = 1 THEN refund_money ELSE 0 END), 0) AS refund_order_1_price',
            'COALESCE(SUM(CASE WHEN status = 2 THEN refund_money ELSE 0 END), 0) AS refund_order_2_price',
            'COALESCE(SUM(CASE WHEN status = 3 THEN refund_money ELSE 0 END), 0) AS refund_order_3_price',
            'COALESCE(SUM(CASE WHEN status = 4 THEN refund_money ELSE 0 END), 0) AS refund_order_4_price',
            'COALESCE(SUM(CASE WHEN status = 5 THEN refund_money ELSE 0 END), 0) AS refund_order_5_price',

            // out_price “审核通过的”退款金额总和
            'COALESCE(SUM(CASE WHEN status in (2,3,5) THEN refund_money ELSE 0 END), 0) AS out_price',
        ];
        $items2 = \think\facade\Db::table('order_refund')
            ->field($field2)
            ->whereBetweenTime('create_at', $date, $end)
            ->group('shop_id')
            ->select()->toArray();
        // echo \think\facade\Db::table('order_refund')->getlastsql();
        // var_dump($items);exit;
        $shop_ids  = empty($items) ? [] : array_column($items, 'shop_id');
        $shop_ids2 = empty($items2) ? [] : array_column($items2, 'shop_id');
        if (empty($shop_ids) && empty($shop_ids2)) {
            return [];
        }
        $map1     = empty($items) ? [] : array_column($items, null, 'shop_id');
        $map2     = empty($items2) ? [] : array_column($items2, null, 'shop_id');
        $shop_ids = array_merge($shop_ids, $shop_ids2);
        $arr      = [];
        foreach ($shop_ids as $shop_id) {
            $v1    = $map1[$shop_id] ?? [];
            $v2    = $map2[$shop_id] ?? [];
            $arr[] = [
                'date'                  => $date,
                'shop_id'               => $shop_id,

                'order_member_count'    => $v1['order_member_count'] ?? 0,
                'order_total'           => $v1['order_total'] ?? 0,
                'pay_order_total'       => $v1['pay_order_total'] ?? 0,
                'order_total_price'     => $v1['order_total_price'] ?? 0,
                'pay_order_total_price' => $v1['pay_order_total_price'] ?? 0,

                'out_price'             => $v2['out_price'] ?? 0,
                'refund_order_total'    => $v2['refund_order_total'] ?? 0,
                'refund_member_count'   => $v2['refund_member_count'] ?? 0,
                'refund_order_0'        => $v2['refund_order_0'] ?? 0,
                'refund_order_1'        => $v2['refund_order_1'] ?? 0,
                'refund_order_2'        => $v2['refund_order_2'] ?? 0,
                'refund_order_3'        => $v2['refund_order_3'] ?? 0,
                'refund_order_4'        => $v2['refund_order_4'] ?? 0,
                'refund_order_5'        => $v2['refund_order_5'] ?? 0,
                'refund_order_0_price'  => $v2['refund_order_0_price'] ?? 0,
                'refund_order_1_price'  => $v2['refund_order_1_price'] ?? 0,
                'refund_order_2_price'  => $v2['refund_order_2_price'] ?? 0,
                'refund_order_3_price'  => $v2['refund_order_3_price'] ?? 0,
                'refund_order_4_price'  => $v2['refund_order_4_price'] ?? 0,
                'refund_order_5_price'  => $v2['refund_order_5_price'] ?? 0,
            ];
        }
        return $arr;
    }
}
